package com.slanmao.controller;

import com.slanmao.common.entity.*;
import com.slanmao.common.utils.SerializeXmlUtil;
import com.slanmao.common.utils.SpringContextUtils;
import com.slanmao.entity.AreaServ;
import com.slanmao.entity.Reply;
import com.slanmao.service.AreaServService;
import com.slanmao.service.ReplyService;
import com.thoughtworks.xstream.XStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.*;

/**
 * <CODE>MessageHanlder</CODE>
 * 消息处理中心
 * @author fenrir
 * @Date 18-12-7
 */
@Slf4j
public class MessageHandler {

    private static AreaServService areaServService;

    private static ReplyService replyService;

    static {
        MessageHandler.areaServService= SpringContextUtils.getBean(AreaServService.class);
        MessageHandler.replyService= SpringContextUtils.getBean(ReplyService.class);

    }

    public static String handleImage(InputMessage inputMsg) {
        // 将POST流转换为XStream对象
        XStream xs = SerializeXmlUtil.createXstream();
        xs.processAnnotations(InputMessage.class);
        xs.processAnnotations(OutputMessage.class);
        xs.alias("xml",InputMessage.class);
        // 取得消息类型
        String msgType = inputMsg.getMsgType();
        Long returnTime = Calendar.getInstance().getTimeInMillis() / 1000;// 返回时间
        String servername = inputMsg.getToUserName();// 服务端
        String custermname = inputMsg.getFromUserName();// 客户端
        log.info("获取多媒体信息");
        log.info("多媒体文件id：" + inputMsg.getMediaId());
        log.info("图片链接：" + inputMsg.getPicUrl());
        log.info("消息id，64位整型：" + inputMsg.getMsgId());

        OutputMessage outputMsg = new OutputMessage();
        outputMsg.setFromUserName(servername);
        outputMsg.setToUserName(custermname);
        outputMsg.setCreateTime(returnTime);
        outputMsg.setMsgType(msgType);
        ImageMessage images = new ImageMessage();
        images.setMediaId(inputMsg.getMediaId());
        outputMsg.setImage(images);
        System.out.println("xml转换：/n" + xs.toXML(outputMsg));
        return xs.toXML(outputMsg);
    }

    public static String handleText(int replyType, InputMessage inputMsg) {
        XStream xs = SerializeXmlUtil.createXstream();
        xs.processAnnotations(InputMessage.class);
        xs.processAnnotations(OutputMessage.class);
        xs.alias("xml",InputMessage.class);
        // 取得消息类型
        String msgType = inputMsg.getMsgType();
        long createTime = inputMsg.getCreateTime();// 接收时间
        Long returnTime = Calendar.getInstance().getTimeInMillis() / 1000;// 返回时间
        String servername = inputMsg.getToUserName();// 服务端
        String custermname = inputMsg.getFromUserName();// 客户端
        String keyword = inputMsg.getContent();
        String result = null;
        // 文本消息
        log.info("开发者微信号：" + inputMsg.getToUserName());
        log.info("发送方帐号：" + inputMsg.getFromUserName());
        log.info("消息创建时间：" + inputMsg.getCreateTime() + new Date(createTime * 1000L));
        log.info("消息内容：" + keyword);
        log.info("消息Id：" + inputMsg.getMsgId());

        AreaServ areaServ = areaServService.findByKeyWord(keyword);
        if (areaServ!=null){
            result = areaServ.toString();
        }else {
            //去查关键词呗
            Reply reply = replyService.findReply(keyword);
            //都没有就给个默认值
            if (reply==null){
                result = "  T_TSorry，您要查询的信息还没有。\n" +
                        "  您也可以查询其他地区关键词。\n" +
                        "  不要紧，小蓝帽已记录您的需求，会在之后为您完善的^_^。";
            }else {
                //文字
                replyType = reply.getType();
                result = reply.getReply();
            }
        }

        switch (replyType){
            //文字回复
            case 0 :
                StringBuffer str = new StringBuffer();
                str.append("<xml>");
                str.append("<ToUserName><![CDATA[" + custermname + "]]></ToUserName>");
                str.append("<FromUserName><![CDATA[" + servername + "]]></FromUserName>");
                str.append("<CreateTime>" + returnTime + "</CreateTime>");
                str.append("<MsgType><![CDATA[" + msgType + "]]></MsgType>");
                str.append("<Content><![CDATA[" + result + "]]></Content>");
                str.append("</xml>");
                log.info(str.toString());
                return str.toString();
            //图片回复
            case 1:
                OutputMessage outputMsg = new OutputMessage();
                outputMsg.setFromUserName(servername);
                outputMsg.setToUserName(custermname);
                outputMsg.setCreateTime(returnTime);
                outputMsg.setMsgType("image");
                ImageMessage images = new ImageMessage();
                images.setMediaId(result);
                outputMsg.setImage(images);
                System.out.println("xml转换：/n" + xs.toXML(outputMsg));
                return xs.toXML(outputMsg);
        }
        return "success";
    }

    public static String handlerEvent(InputMessage inputMsg){
        log.info("进入场景模式");
        // 将POST流转换为XStream对象
        XStream xs = SerializeXmlUtil.createXstream();
        xs.processAnnotations(NewsMessage.class);
        xs.alias("xml",NewsMessage.class);
        // 取得消息类型
        Long returnTime = Calendar.getInstance().getTimeInMillis() / 1000;// 返回时间
        String servername = inputMsg.getToUserName();// 服务端
        log.info("服务器"+servername);
        String custermname = inputMsg.getFromUserName();// 客户端
        log.info("来源"+custermname);
        String event = inputMsg.getEvent();
        String eventKey = inputMsg.getEventKey();
        List<NewsItem> itemList = new ArrayList<>();
        switch (event)
        {

            //用户订阅
            case "subscribe":
                log.info("进入订阅回复");
                NewsMessage message = new NewsMessage();
                message.setCreateTime(returnTime);
                message.setCount(1);
                message.setFromUserName(servername);
                message.setToUserName(custermname);
                NewsItem item = new NewsItem();
                item.setDescription("小蓝帽（湖北）信息科技有限公司，“小蓝帽”致力于解决用户安全常识匮乏引起的燃气事故频发，杜绝因使用不当和维修不及时导致的安全隐患，为企业及用户提供成熟安全系统服务");
                item.setPicurl("http://slanmao.com/wp-content/uploads/2019/03/worder.png");
                item.setTitle("关于小蓝帽");
                item.setUrl("http://slanmao.com/aboutslanmao");
                itemList.add(item);
                //如果用户扫描工单码则微信会同时推送工单信息,及时回复工单
                if (eventKey !=null&&inputMsg.getTicket()!=null){
                    message.setCount(2);
                    log.info("进去回复工单");
                    NewsItem orderInfo = new NewsItem();
                    orderInfo.setDescription("请查收您的工单信息");
                    orderInfo.setPicurl("http://slanmao.com/wp-content/uploads/2019/03/abutslanmao.png");
                    orderInfo.setTitle("隐患整改通知书");
                    String openid = inputMsg.getFromUserName();
                    //订阅后推送的工单ID是在EventKey中以qrscene_****的形式出现的,只取后面的值
                    String orderId = eventKey.substring(8);
                    String url = String.format("https://app.slanmao.com/check_list/index.html?id=%s", orderId);
                    orderInfo.setUrl(url);
                    itemList.add(orderInfo);
                }
                message.setArticles(itemList);
                return xs.toXML(message);
            //扫码推事件且弹出“消息接收中”提示框的事件推送
            case "SCAN":
                log.info("进入扫码回复");
                NewsMessage order = new NewsMessage();
                order.setCreateTime(returnTime);
                order.setCount(1);
                order.setFromUserName(servername);
                order.setToUserName(custermname);
                NewsItem orderInfo = new NewsItem();
                orderInfo.setDescription("隐患整改通知书");
                orderInfo.setPicurl("http://slanmao.com/wp-content/uploads/2019/03/abutslanmao.png");
                orderInfo.setTitle("隐患整改通知书");
                String openid = inputMsg.getFromUserName();
                String orderId = eventKey;
                String url = String.format("https://app.slanmao.com/check_list/index.html?id=%s", orderId);
                orderInfo.setUrl(url);
                itemList.add(orderInfo);
                order.setArticles(itemList);
                return xs.toXML(order);
           default:
               log.info("没有回复");
               return "success";
        }
    }

    public static Boolean verifyInfo(String signature, String timestamp, String nonce,
                              String token) {
        TreeSet<String> set = new TreeSet<String>();
        set.add(token);
        set.add(timestamp);
        set.add(nonce);
        StringBuilder sBuilder = new StringBuilder();
        for (String item : set) {
            sBuilder.append(item);
        }
        String sign = DigestUtils.sha1Hex(sBuilder.toString());
        return signature.equalsIgnoreCase(sign);
    }




}
